import os
from time import sleep

# withOpen: 代码执行结束, 系统会自动调用 close方法
with open("test-with.txt", "w", encoding="utf-8") as f:
    f.write("Hello, World!\n")
    print(f.closed) # False, 文件未关闭
print(f.closed) # True, 文件已关闭


# encoding: 指定文件的编码格式, 默认为系统默认编码, 可以指定为utf-8, gbk等
with open("test-encoding.txt", "w", encoding="utf-8") as f:
    f.write("Hello, World! 你好，世界！\n")
    print(f.closed) # False, 文件未关闭

with open("test-encoding.txt", "r", encoding="utf-8") as f:
    content = f.read()
    print(content) # Hello, World! 你好，世界！
    print(f.closed) # False, 文件未关闭


# DEMO: 图片复制 rb 模式: read binary, wb 模式: write binary
with open("../images/mountain.jpeg","rb") as img:
    content1 = img.read()
    print(content1)
with open("../images/mountain_copy.jpeg","wb") as img_copy:
    img_copy.write(content1)
    print("图片复制完成")

sleep(3)
os.remove("../images/mountain_copy.jpeg")  # 刪除复制的图片